let socketOpen = false;

function connectWebSocket(token) {
	uni.connectSocket({
		url: 'ws://localhost:8501/websocket',
		header: {
			'token': token
		},
		success: function() {
			console.log('WebSocket connection established.');
		}
	})
	uni.onSocketOpen(function(res) {
		socketOpen = true;
		//连接成功发送信息，将token与session绑定在一起
		const socketMessage = {
			'userId': 0,
			'sender': 1,
			'content': token,
			'messageType': 0
		}
		uni.sendSocketMessage({
			data: JSON.stringify(socketMessage),
			success: (res) => {
				console.log('成功连接并绑定id');
			},
			fail: (err) => {
				console.log('失败');
			}
		})
	});

	uni.onSocketClose(function(res) {
		socketOpen = false;
		console.log('WebSocket 已关闭！');
		//异常退出，重新连接
		if(uni.getStorageSync('TOKEN')){
			connectWebSocket()
		}
	});
}

function sendSocketMessage(content, messageType) {

	if (socketOpen) {
		//连接成功发送信息，将token与session绑定在一起
		const socketMessage = {
			'userId': 0,
			'sender': 1,
			'content': content,
			'messageType': messageType
		}
		uni.sendSocketMessage({
			data: JSON.stringify(socketMessage),
			success: (res) => {
				console.log('成功发送消息');
			},
			fail: (err) => {
				console.log('发送消息失败');
			}
		})
	} else {
		console.log('无法发送，socket已关闭')
	}
}


export default {
	connectWebSocket,
	sendSocketMessage
};
